import datetime
import logging

from fastapi.routing import APIRouter
from starlette.status import HTTP_404_NOT_FOUND
from tortoise.contrib.pydantic import pydantic_model_creator

from ModelPydantic import KumquatIn
from models import Kumquat

kumquat = APIRouter()


@kumquat.get("/schema", tags=["Get Kumquat Schema"], summary="Well it's not readable...",
             description="Schema Test",
             response_description="Return the Kumquat Schema")
async def get_kumquat_schema():
    kumquatPydantic = pydantic_model_creator(Kumquat)
    return {'message': kumquatPydantic.model_json_schema()}


@kumquat.get("/all", tags=["Get All kumquats"], summary="List All kumquats",
             description="Fetches a list of all kumquat records.",
             response_description="A list of all kumquats is returned.")
async def get_all_kumquat():
    kumquats = await Kumquat.all()
    return {'message': 'OK', 'data': kumquats}, 200


@kumquat.get("/<kumquat_id>", tags=["Get Single kumquat"], summary="Find kumquat by ID",
             description="Retrieves a single kumquat record based on the provided kumquat ID.",
             response_description="The matching kumquat record is returned.")
async def get_kumquat_id(kumquat_id):
    kumquatById = await Kumquat.filter(id=kumquat_id)
    return {"message": 'OK', 'data': kumquatById}, 200


@kumquat.get("/", tags=["Search kumquats"], summary="Search kumquats by Criteria",
             description="Searches for kumquats based on specified name, address, presenter, and phone number.",
             response_description="A list of kumquats matching the criteria is returned.")
async def get_kumquat(name, style, note):
    filters = {}
    if name != 'None':
        filters['name'] = name
    if style != 'None':
        filters['style'] = style
    if note != 'None':
        filters['note'] = note

    kumquatFound = await Kumquat.filter(**filters)
    if not kumquatFound:
        return
    return {"message": 'OK', 'data': kumquatFound}, 200


@kumquat.post("/", tags=["Insert to kumquat"])
async def add_kumquat(kumquatIn: KumquatIn):
    kumquatInsert = Kumquat(name=kumquatIn.name, style=kumquatIn.style,
                            original_price=kumquatIn.original_price, price=kumquatIn.price,
                            note=kumquatIn.note)
    kumquatInsert.profit = kumquatInsert.price - kumquatInsert.original_price
    if kumquatInsert.note == 'CURRENT':
        # Set the same name,style kumquat note to OLD
        kumquatToUpdate = await Kumquat.filter(name=kumquatInsert.name, style=kumquatInsert.style,
                                               note='CURRENT').update(note='OLD')
        if not kumquatToUpdate:
            print(f"UPDATE THE {kumquatInsert.name} / {kumquatInsert.style} FROM CURRENT TO OLD.")
        else:
            kumquatInsert.price_date = datetime.datetime.now(datetime.UTC)
            print(f"INSERT A NEW FORMAT KUMQUAT FOR {kumquatInsert.name} {kumquatInsert.style} demi-kilo.")
    await kumquatInsert.save()
    return {"message": "OK"}, 201


@kumquat.get("/format", tags=['Get unique kumquat name and style'])
async def get_kumquat_name():
    kumquatFormat = await Kumquat.filter().distinct().values('name', 'style')
    return {"message": 'OK', 'data': kumquatFormat}, 201


@kumquat.delete("/")
async def del_kumquat(name, style, note):
    filters = {}
    if name != 'None':
        filters['name'] = name
    if style != 'None':
        filters['style'] = style
    if note != 'None':
        filters['note'] = note

    kumquatFound = await Kumquat.filter(**filters).delete()
    if not kumquatFound:
        raise HTTP_404_NOT_FOUND(detail=f"kumquat for {filters} not found.")

    return {"message": 'OK', 'data': kumquatFound}, 201
